
# 2. 自动计算token长度（避免超出限制）
import tiktoken  # 需要安装 pip install tiktoken

def count_tokens(messages):
    encoder = tiktoken.encoding_for_model("deepseek-chat")
    count = 0
    for msg in messages:
        count += len(encoder.encode(msg["content"]))
    return count